package com.ruoyi.system.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.PlanDetails;
import com.ruoyi.system.api.domain.ReportInfo;
import com.ruoyi.system.api.domain.StPhoneReport;
import com.ruoyi.system.api.mapper.PlanDetailsMapper;
import com.ruoyi.system.api.mapper.ReportInfoMapper;
import com.ruoyi.system.api.service.CcService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.StAcceptanceReportMapper;
import com.ruoyi.system.api.domain.StAcceptanceReport;
import com.ruoyi.system.api.service.IStAcceptanceReportService;
import com.ruoyi.common.core.text.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 验收报告 验收报告Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-03-04
 */
@Service
public class StAcceptanceReportServiceImpl implements IStAcceptanceReportService 
{
    private static final Logger log = LoggerFactory.getLogger(StAcceptanceReportServiceImpl.class);

    @Autowired
    private StAcceptanceReportMapper stAcceptanceReportMapper;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    /** 调用CC接口service */
    @Autowired
    private CcService ccService;

    /**
     * 查询验收报告 验收报告
     * 
     * @param id 验收报告 验收报告ID
     * @return 验收报告 验收报告
     */
    @Override
    public StAcceptanceReport selectStAcceptanceReportById(Long id)
    {
        return stAcceptanceReportMapper.selectStAcceptanceReportById(id);
    }

    /**
     * 查询验收报告 验收报告列表
     * 
     * @param stAcceptanceReport 验收报告 验收报告
     * @return 验收报告 验收报告
     */
    @Override
    public List<StAcceptanceReport> selectStAcceptanceReportList(StAcceptanceReport stAcceptanceReport)
    {
        return stAcceptanceReportMapper.selectStAcceptanceReportList(stAcceptanceReport);
    }

    /**
     * 新增验收报告 验收报告
     * 
     * @param stAcceptanceReport 验收报告 验收报告
     * @return 结果
     */
    @Override
    public int insertStAcceptanceReport(StAcceptanceReport stAcceptanceReport)
    {
        stAcceptanceReport.setCreateTime(DateUtils.getNowDate());
        return stAcceptanceReportMapper.insertStAcceptanceReport(stAcceptanceReport);
    }

    /**
     * 修改验收报告 验收报告
     * 
     * @param stAcceptanceReport 验收报告 验收报告
     * @return 结果
     */
    @Override
    public int updateStAcceptanceReport(StAcceptanceReport stAcceptanceReport)
    {
        stAcceptanceReport.setUpdateTime(DateUtils.getNowDate());
        return stAcceptanceReportMapper.updateStAcceptanceReport(stAcceptanceReport);
    }

    /**
     * 删除验收报告 验收报告对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStAcceptanceReportByIds(String ids)
    {
        return stAcceptanceReportMapper.deleteStAcceptanceReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除验收报告 验收报告信息
     * 
     * @param id 验收报告 验收报告ID
     * @return 结果
     */
    @Override
    public int deleteStAcceptanceReportById(Long id)
    {
        return stAcceptanceReportMapper.deleteStAcceptanceReportById(id);
    }

    /**
     *  添加验收报告
     *
     * @param acceptanceReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020-03-02 13:56
     */
    @Override
    public ResponseWithData<?> addAcceptanceReport(StAcceptanceReport acceptanceReport) {
        if (acceptanceReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (acceptanceReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (acceptanceReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == acceptanceReport.getInstallStartTime()) {
            return new ResponseWithData<>().error().msg("installStartTime cannot be empty！");
        }
        if (null == acceptanceReport.getInstallEndTime()) {
            return new ResponseWithData<>().error().msg("installEndTime cannot be empty！");
        }
        if (null == acceptanceReport.getWarrantyStartTime()) {
            return new ResponseWithData<>().error().msg("warrantyStartTime cannot be empty！");
        }
        if (null == acceptanceReport.getWarrantyEndTime()) {
            return new ResponseWithData<>().error().msg("warrantyEndTime cannot be empty！");
        }
        if (null == acceptanceReport.getAcceptanceTime()) {
            return new ResponseWithData<>().error().msg("acceptanceTime cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getComputerMfr())) {
            return new ResponseWithData<>().error().msg("computerMfr cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getModelNumber())) {
            return new ResponseWithData<>().error().msg("modelNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNumber())) {
            return new ResponseWithData<>().error().msg("serviceNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNumber())) {
            return new ResponseWithData<>().error().msg("serviceNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getSoftware())) {
            return new ResponseWithData<>().error().msg("software cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getFseName())) {
            return new ResponseWithData<>().error("fseName cannot be empty！");
        }

        ReportInfo reportInfo = new ReportInfo();
        if (acceptanceReport.getId() == null) {
            acceptanceReport.setDelFlag("0");
            acceptanceReport.setSyncFlag("0");
            acceptanceReport.setCreateTime(new Date());
            acceptanceReport.setCreateBy(acceptanceReport.getEnginnerId() + "");
            stAcceptanceReportMapper.insertStAcceptanceReport(acceptanceReport);

            // 验收报告信息保存到主表 st_acceptance_report

            reportInfo.setServiceNo(acceptanceReport.getServiceNo());
            reportInfo.setEnginnerId(acceptanceReport.getEnginnerId());
            reportInfo.setPlanId(acceptanceReport.getPlanId());
            reportInfo.setRelServiceNo(4L);
            reportInfo.setRelPlanId("st_acceptance_report");
            reportInfo.setBatchType(acceptanceReport.getId());
            reportInfo.setDelFlag("0");
            reportInfo.setCreateTime(new Date());
            reportInfo.setCreateBy(acceptanceReport.getEnginnerId() + "");
            reportInfo.setNoticeId(acceptanceReport.getNoticeId());
            reportInfo.setSyncFlag("0");
            reportInfo.setFseName(acceptanceReport.getFseName());
            // TODO 报告编号生成规则是什么
            reportInfoMapper.insertStReportInfo(reportInfo);
        } else {
            acceptanceReport.setUpdateBy(acceptanceReport.getEnginnerId() + "");
            acceptanceReport.setUpdateTime(new Date());
            stAcceptanceReportMapper.updateStAcceptanceReport(acceptanceReport);
            reportInfo = reportInfoMapper.selectStReportInfoByBatchType(acceptanceReport.getId(), "4");
            reportInfo.setUpdateBy(acceptanceReport.getEnginnerId() + "");
            reportInfo.setUpdateTime(new Date());
           // reportInfo.setEnginnerId(acceptanceReport.getEnginnerId());
            //reportInfo.setFseName(acceptanceReport.getFseName());
            reportInfoMapper.updateStReportInfo(reportInfo);
        }




        return new ResponseWithData<>().success(reportInfo).code(200);
    }

    /**
     *  查看验收报告
     *
     * @param id 验收报告主键ID
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/5 9:31 上午
     */
    @Override
    public ResponseWithData<?> detailAcceptanceReport(Long id) {
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoById(id);
        if (null != reportInfo) {
            StAcceptanceReport stAcceptanceReport = stAcceptanceReportMapper.selectStAcceptanceReportById(reportInfo.getBatchType());
            reportInfo.setReportInfo(stAcceptanceReport);
        }
        return new ResponseWithData<>().success(reportInfo).code(200);
    }

    /**
     *  修改验收报告
     *
     * @param acceptanceReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/5 10:23 上午
     */
    @Override
    public ResponseWithData<?> updateAcceptanceReport(StAcceptanceReport acceptanceReport) {
        if (acceptanceReport.getId() == null) {
            return new ResponseWithData<>().error("id cannot be empty！");
        }
        if (acceptanceReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (acceptanceReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (acceptanceReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == acceptanceReport.getInstallStartTime()) {
            return new ResponseWithData<>().error().msg("installStartTime cannot be empty！");
        }
        if (null == acceptanceReport.getInstallEndTime()) {
            return new ResponseWithData<>().error().msg("installEndTime cannot be empty！");
        }
        if (null == acceptanceReport.getWarrantyStartTime()) {
            return new ResponseWithData<>().error().msg("warrantyStartTime cannot be empty！");
        }
        if (null == acceptanceReport.getWarrantyEndTime()) {
            return new ResponseWithData<>().error().msg("warrantyEndTime cannot be empty！");
        }
        if (null == acceptanceReport.getAcceptanceTime()) {
            return new ResponseWithData<>().error().msg("acceptanceTime cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getComputerMfr())) {
            return new ResponseWithData<>().error().msg("computerMfr cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getModelNumber())) {
            return new ResponseWithData<>().error().msg("modelNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNumber())) {
            return new ResponseWithData<>().error().msg("serviceNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getServiceNumber())) {
            return new ResponseWithData<>().error().msg("serviceNumber cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getSoftware())) {
            return new ResponseWithData<>().error().msg("software cannot be empty！");
        }
        if (StringUtils.isEmpty(acceptanceReport.getFseName())) {
            return new ResponseWithData<>().error("fseName cannot be empty！");
        }

        acceptanceReport.setUpdateBy(acceptanceReport.getEnginnerId() + "");
        acceptanceReport.setUpdateTime(new Date());
        stAcceptanceReportMapper.updateStAcceptanceReport(acceptanceReport);

        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(acceptanceReport.getId(), "4");
        reportInfo.setUpdateBy(acceptanceReport.getEnginnerId() + "");
        reportInfo.setUpdateTime(new Date());
      //  reportInfo.setEnginnerId(acceptanceReport.getEnginnerId());
        //reportInfo.setFseName(acceptanceReport.getFseName());
        reportInfoMapper.updateStReportInfo(reportInfo);

        return new ResponseWithData<>().success(acceptanceReport).code(200);
    }

    /**
     *  提交验收报告
     *
     * @param id 提交验收报告主键ID
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/7 10:29 上午
     */
    @Override
    public ResponseWithData<?> acceptanceReportSubmit(Long id, Long enginnerId) {
        if (null == id) {
            return new ResponseWithData<>().error().msg("id cannot be empty");
        }
        if (null == enginnerId) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }

        StAcceptanceReport stAcceptanceReport = stAcceptanceReportMapper.selectStAcceptanceReportById(id);
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(id, "4");

        if (!(enginnerId+"").equals(reportInfo.getEnginnerId()+"")) {
            String name=reportInfo.getFseName();
            return new ResponseWithData<>().error().msg("你不能提交"+name+"的报告, 如需提交请联系"+name);
        }

        if (null == stAcceptanceReport || null == reportInfo) {
            return new ResponseWithData<>().error().msg("验收报告不存在");
        }
        if ("1".equals(reportInfo.getSyncFlag())) {
            return new ResponseWithData<>().error().msg("此验收报告已提交过");
        }

        Map<String, String> params = new HashMap<>();
        // 唯一主键
        params.put("report_guid", reportInfo.getId().toString());
        // Service号
        params.put("service_no", reportInfo.getServiceNo());
        // 提交的工程师ID
        params.put("enginner_id", enginnerId + "");
        //  安装开始时间
        params.put("install_start_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stAcceptanceReport.getInstallStartTime()));
        //  安装结束时间
        params.put("install_end_time",  DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stAcceptanceReport.getInstallEndTime()));
        // 保修开始时间
        params.put("warranty_start_time",  DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stAcceptanceReport.getWarrantyStartTime()));
        // 保修结束时间
        params.put("warranty_end_time",  DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stAcceptanceReport.getWarrantyEndTime()));
        // 验收时间
        params.put("acceptance_time",  DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stAcceptanceReport.getAcceptanceTime()));
        // 电脑厂家
        params.put("computer_mfr", stAcceptanceReport.getComputerMfr());
        // 电脑型号
        params.put("model_number", stAcceptanceReport.getModelNumber());
        // 服务号
        params.put("service_number", stAcceptanceReport.getServiceNumber());
        // 操作系统
        params.put("software", stAcceptanceReport.getSoftware());
        // 选项软件
        params.put("option_software", stAcceptanceReport.getOptionSoftware());
        // 系统软件
        params.put("SysSoft", stAcceptanceReport.getSyssoft());



        // 请求CC接口 提交电话解决报告
        String response = ccService.installReceivingReporthandle(params);

        /** 如果调用接口异常直接返回 */
        if(null == response){
            return new ResponseWithData().error().msg("提交验收报告失败 调用CC端提交验收报告接口发生异常").code(202);
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            String rptNo = "";
            try {
                JSONArray record = jsonObject.getJSONArray("record");
                if (record != null && record.size() > 0) {
                    rptNo = record.getJSONObject(0).getString("rpt_no");
                }
            } catch (Exception e) {
                log.error("程序异常", e.getMessage());
            }


            // 提交成功 ，更新同步状态
            ReportInfo info = new ReportInfo();
            info.setId(reportInfo.getId());
            info.setSyncFlag("1");
            info.setSyncTime(new Date());
            info.setReportNo(rptNo);
            reportInfoMapper.updateStReportInfo(info);

            return new ResponseWithData().success().msg("提交验收报告成功").code(200);
        } else if ("2".equals(status)) {
            String message = jsonObject.getString("message");
            return new ResponseWithData().error().msg(message).code(201);
        } else {
            return new ResponseWithData().error().msg("提交验收报告失败 调用CC端提交验收报告接口发生异常").code(201);
        }
    }
}
